package com.kuang.single;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @program: juc
 * @description: 懒汉式单例
 * @author: 陈恩涛
 * @create: 2021-03-25 16:57
 **/
public class LazyMan {

    private static boolean qinjiang = false;

    private LazyMan() {
        synchronized (LazyMan.class) {
            if (!qinjiang) {
                qinjiang = true;
            } else {
                throw new RuntimeException("不要试图通过反射破坏单例！");
            }
        }
    }

    private volatile static LazyMan lazyMan;

    public static LazyMan getInstance() {

        // 双重检测锁模式的懒汉式单例    DCL懒汉式
        if (lazyMan == null) {
            synchronized (LazyMan.class) {
                if (lazyMan == null) {
                    lazyMan = new LazyMan();
                }
            }
        }
        return lazyMan;
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        //LazyMan instance = LazyMan.getInstance();

        //反射可以无视私有，可以破坏这种单例
        Field qinjiang = LazyMan.class.getDeclaredField("qinjiang");
        qinjiang.setAccessible(true);
        Constructor<LazyMan> dc = LazyMan.class.getDeclaredConstructor(null);
        dc.setAccessible(true);
        LazyMan instance = dc.newInstance();
        qinjiang.set(instance,false);
        LazyMan instance2 = dc.newInstance();

        System.out.println(instance);
        System.out.println(instance2);
    }

}
